package cn.admin.configcenter.registry.service.client;

import cn.admin.config.common.Revision;
import cn.admin.config.common.protocol.Swizzle;
import cn.admin.configcenter.registry.common.info.ClientConnection;
import cn.admin.configcenter.registry.common.info.GroupId;
import cn.admin.configcenter.registry.service.DataSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.*;

public class NonPersistDataSource implements DataSource {

	private static final Logger log = LoggerFactory.getLogger(NonPersistDataSource.class);
	private final NonPersistDataMerge dataMerge;

	public NonPersistDataSource(NonPersistDataMerge dataMerge) {
		this.dataMerge = dataMerge;
	}

	@Override
	public void addPublisher(ClientConnection client, GroupId group, String clientId, String datumId) {
		client.addPublisher(group,clientId);
	}

	@Override
	public void publishData(ClientConnection client, GroupId group,
	                        String clientId, List<Swizzle> data, Revision newRev) {
		if (data.isEmpty()) {
			client.removePublisher(group,clientId);
		} else {
			client.publishData(group,data.get(0),newRev);
		}
	}

	@Override
	public void addSubscriber(ClientConnection client, GroupId group, String clientId) {
		client.addSubscriber(group,clientId);
	}

	@Override
	public List<Swizzle> getData(GroupId group) throws Exception {
		return new ArrayList<>(this.getDatumData(group).values());
	}

	@Override
	public List<Swizzle> getPushData(GroupId group) throws Exception {
		List<Swizzle> result = new LinkedList<>();
		Map<String,Swizzle> datum2data = getDatumData(group);
		for (Map.Entry<String, Swizzle> entry : datum2data.entrySet()) {
			Swizzle data = entry.getValue();
			result.add(data);
		}
		return result;
	}

	@Override
	public Map<String, Swizzle> getDatumData(GroupId group) {
		return dataMerge.getDatumData(group);
	}

	@Override
	public List<GroupId> allDataGroups() throws Exception {
		return dataMerge.allDataGroup();
	}

	static String getIp(String hostId) {
		int idx = hostId.indexOf(58);
		return idx >= 0 ? hostId.substring(0, idx) : hostId;
	}

}
